﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Globalization;

namespace BSC_OTC_Management.UserControls
{
    public partial class Transaction_Approval : UserControl
    {
        #region Khai bao bien
        string _formName = "BSC_TBL_TLLOGALL";
        string _operator = "";
        string _fieldtype = "";
        string _lookupcmdsql = "";
        Code.CL_Ultility _cl = new Code.CL_Ultility();
        DataTable _tableView = new DataTable("View");
        DataTable _tableTrans = new DataTable("Transaction");
        Hashtable listTieuChi = new Hashtable();
        Hashtable listDS_DK_TimKiem = new Hashtable();
        DataTable _tableTieuChi = new DataTable("SEARCHFLD");
        DataTable _tableResult = new DataTable("BSC_TBL_TLLOGALL");
        #endregion

        public Transaction_Approval(int _width, int _height)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            this.Width = _width;
            this.Height = _height;
            this.dgvResult.CellFormatting += new DataGridViewCellFormattingEventHandler(dgvResult_CellFormatting);
            //hiển thị tên cột theo tiếng việt
            _tableView = _cl._services.GetViewBy_SearchCode(_formName);
            //lấy phép toán tìm kiếm:Like, = , >, <
            _tableTieuChi = _cl._services.GetPhepToanBy_SearchCode(_formName);
            //hiển thị trên cbb
            FillTieuChi(_tableTieuChi);
            //06-08-2017:DATNT:disable các btn có quyền mới enable 
            this.btnApprove.Enabled = false;
            this.btnDelete.Enabled = false;
            this.btnReject.Enabled = false;
            this.btnView.Enabled = true;
        }
        
        public void LoadTransData()
        {
            try
            {
                string str = "";
                DataTable table = new DataTable("noname");
                table.Columns.Add("COLUMNNAME");
                table.Columns.Add("PHEPTINH");
                table.Columns.Add("VALUE");
                table.Columns.Add("DATATYPE");
                if (this.clbDanhSachDieuKien.Items.Count > 0)
                {
                    foreach (DictionaryEntry entry in this.listDS_DK_TimKiem)
                    {
                        string[] strKey = entry.Key.ToString().Split(new string[] { "@@@" }, StringSplitOptions.None);
                        string[] strArray = entry.Value.ToString().Split(new string[] { "@@@" }, StringSplitOptions.None);


                        DataRow row = table.NewRow();
                        row["COLUMNNAME"] = strKey[0];
                        row["PHEPTINH"] = strArray[0];
                        if (strKey[1] == "D")
                        {
                            DateTime time = DateTime.ParseExact(strArray[1], "dd/MM/yyyy", CultureInfo.InvariantCulture);
                            row["VALUE"] = time.ToString("dd/MM/yyyy");
                        }
                        else
                            row["VALUE"] = strArray[1];
                        row["DATATYPE"] = strKey[1];
                        table.Rows.Add(row);
                        /*}
                        else
                        {
                            string[] strArray2 = entry.Value.ToString().Split(new string[] { "@@@" }, StringSplitOptions.None);
                            DataRow row = table.NewRow();
                            row["COLUMNNAME"] = entry.Key;
                            row["PHEPTINH"] = strArray2[0];
                            row["VALUE"] = strArray2[1];
                            row["DATATYPE"] = "T";
                            table.Rows.Add(row);
                        }*/
                    }
                }
                this._tableResult = this._cl._services.SearchView_ByParameters(this._formName, table);
                // Xử lý dữ liệu giao dịch theo phân quyền trước khi show ra
                this.ProcessPermissionBeforeShow();
                /*đổ dữ liệu lên datagridview*/
                ShowResult(_tableResult);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,Code.StaticVariable.messeseboxLuuY);
            }
        }

        // hàm này để kiêm tra xem USER có quyền xem với giao dịch đó hay ko, nếu ko thì remove ko cho hiện
        private void ProcessPermissionBeforeShow()
        {
            for (int i = this._tableResult.Rows.Count -1; i >= 0; i--)
            {
                DataRow row_i = this._tableResult.Rows[i];
                bool check = false;
                for (int j = 0; j < Code.StaticVariable.tablePermission.Rows.Count; j++)
                {
                    DataRow row_j = Code.StaticVariable.tablePermission.Rows[j];
                    if (Convert.ToString(row_i["menuid"]) == Convert.ToString(row_j["menuid"])) 
                    {
                        string _authcode = Convert.ToString(row_j["authcode"]);
                        // kiểm tra nếu là trống thì ko show ra giao dịch này
                        if (_authcode == "")
                        {
                            this._tableResult.Rows.RemoveAt(i);
                        }
                        else
                        {
                            // kiểm tra nếu là N ( không có quyền xem) thì ko show ra giao dịch này
                            if (_authcode.ToCharArray()[0] == 'N')
                            {
                                this._tableResult.Rows.RemoveAt(i);
                            }
                        }
                        check = true;
                        break;
                    }
                }
                if (check == false)
                {
                     this._tableResult.Rows.RemoveAt(i);
                }
            }
        }

        private void FillTieuChi(DataTable _table)
        {
            foreach (DataRow row in _table.Rows)
            {
                string key = String.Concat(row["fldcd"].ToString().Trim(), '.', row["fieldcode"].ToString().Trim(),"@@@", row["fieldtype"].ToString());
                string value = row["fieldname"].ToString();
                this.listTieuChi.Add(key, value);
                this.cbbTieuChi.Items.Add(value);
            }

            //DATNT: chọn item đầu tiên đổ cho combobox
            if (listTieuChi.Count > 0)
            {
                this.cbbTieuChi.SelectedIndex = 0;
            }
        }

        private void ShowResult(DataTable _e)
        {
            // An cot menuid

            //convert _e to View
            DataTable view = new DataTable("View");
            foreach (DataColumn col in _e.Columns)
            {
                if (col.ColumnName == "DUYET")
                    view.Columns.Add(col.ColumnName, typeof(String));
                else
                    view.Columns.Add(col.ColumnName, col.DataType);
            }

            for (int i = 0; i < _e.Rows.Count; i++)
            {
                view.Rows.Add(_e.Rows[i].ItemArray);
            }

            //add duyet
            DataTable tblduyet = new DataTable("Duyet");
            tblduyet = _cl._services.GetDatatable_BySQL("select * from allcode where cdtype = 'AP' and cdname = 'DUYET' and cduser='Y' ORDER BY lstodr");
            for (int i = 0; i < view.Rows.Count; i++)
            {
                for (int j = 0; j < tblduyet.Rows.Count; j++)
                {
                    if (view.Rows[i]["DUYET"].ToString() == tblduyet.Rows[j]["CDVAL"].ToString())
                        view.Rows[i]["DUYET"] = tblduyet.Rows[j]["CDCONTENT"];
                }
            }

            // Thay tên dựa theo FieldCode, FieldName
            this.dgvResult.DataSource = view;

            foreach (DataGridViewColumn column in this.dgvResult.Columns)
            {
                // kiem tra, neu column datatype = decimal --> format kieu khac
                if (column.ValueType == typeof(System.Decimal))
                {
                    column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    column.DefaultCellStyle.Format = "#,##0.###";
                }

                foreach (DataRow row in _tableView.Rows)
                {
                    if (row["fldname"].ToString() == column.HeaderText)
                    {
                        column.HeaderText = row["caption"].ToString();
                    }
                }
            }
        }

        private void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                //kiểm tra xem đã duyệt chưa?
                // lấy ID của row được chọn
                string _id = this.dgvResult.SelectedRows[0].Cells["AUTOID"].Value.ToString();
                string _ColumnName = this.dgvResult.Columns[0].Name;
                string _tblName = "";
                string _store = "";
                //Hiển thị Dialog thông báo
                DialogResult dialog = MessageBox.Show(Code.StaticVariable.messeseboxDuyetRow, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.YesNo);

                if (dialog == DialogResult.Yes)
                {
                    int magiaodich = Convert.ToInt16(this.dgvResult.SelectedRows[0].Cells["MAGIAODICH"].Value.ToString());
                    int check = _cl._services.CheckApprove(_formName, _ColumnName, _id);

                    //dữ liệu chưa được duyệt
                    if (check == (int)Code.StaticVariable.approveCase.ChuaDuyet)
                    {

                        //thực thi giao dịch
                        switch (magiaodich)
                        {
                            case 203:
                                _tblName = "BSC_TBL_CHUYENNHUONG";
                                _store = "bsc_203.Chuyen_nhuong";
                                break;
                            case 207:
                                _tblName = "BSC_TBL_PHONGTOA";
                                _store = "bsc_207.Phong_toa_tp";
                                break;
                            case 208:
                                _tblName = "BSC_TBL_GIAIPHONGTOA";
                                _store = "bsc_208.Giai_toa_tp";
                                break;
                            case 209:
                                _tblName = "BSC_TBL_CAMCO";
                                _store = "bsc_209.Cam_co_tp";
                                break;
                            case 210:
                                _tblName = "BSC_TBL_GIAICAMCO";
                                _store = "bsc_210.Giai_cam_co_tp";
                                break;
                            case 211:
                                _tblName = "BSC_TBL_MUALAI";
                                _store = "bsc_211.Mua_lai_tp";
                                break;
                            case 602:
                                _tblName = "BSC_TBL_NOPTIEN";
                                _store = "bsc_602.Nop_tien_mat";
                                break;
                            case 603:
                                _tblName = "BSC_TBL_RUTTIEN";
                                _store = "bsc_603.Rut_tien_mat";
                                break;
                            case 604:
                                _tblName = "BSC_TBL_PHONGTOATIEN";
                                _store = "bsc_604.Phong_toa_tien";
                                break;
                            case 605:
                                _tblName = "BSC_TBL_GIAITOATIEN";
                                _store = "bsc_605.Giai_toa_tien";
                                break;

                            default:
                                break;
                        }

                        if (_tblName.Length == 0)
                            throw new Exception("Không có giao dịch này!");
                        //get table transaction data  "select c.*,t.ngaytaogd from " + _tblName + " c, " + _formName + " t  where c.idgd = t.autoid and c.IDGD ='" + _id + "'"
                        _tableTrans = _cl._services.GetDatatable_BySQL("select c.*,t.ngaytaogd from " + _tblName + " c, " + _formName + " t  where c.idgd = t.autoid and c.IDGD ='" + _id + "'");

                        //bien tra ve kq co chấp nhận duyet hay ko? có = đã duyệt
                        int duyet = (int)Code.StaticVariable.approveCase.ChuaDuyet;
                        //show lại màn hình giao dịch cho dvck xem lại
                        DataTable dt = _cl._services.GetMenu_ByMenuCode(Convert.ToString(magiaodich));
                        if (dt.Rows.Count > 0)
                        {
                            string _formname = Convert.ToString(dt.Rows[0]["formname"]);
                            switch (_formname)
                            {
                                case "Frm_ChuyenNhuong":
                                    Forms.SoTraiChu.Frm_ChuyenNhuong _Frm_ChuyenNhuong = new Forms.SoTraiChu.Frm_ChuyenNhuong(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_ChuyenNhuong.ShowDialog();
                                    duyet = _Frm_ChuyenNhuong._duyet;
                                    break;
                                case "Frm_PhongToa":
                                    Forms.SoTraiChu.Frm_PhongToa _Frm_PhongToa = new Forms.SoTraiChu.Frm_PhongToa(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_PhongToa.ShowDialog();
                                    duyet = _Frm_PhongToa._duyet;
                                    break;
                                case "Frm_GiaiPhongToa":
                                    Forms.SoTraiChu.Frm_GiaiPhongToa _Frm_GiaiPhongToa = new Forms.SoTraiChu.Frm_GiaiPhongToa(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_GiaiPhongToa.ShowDialog();
                                    duyet = _Frm_GiaiPhongToa._duyet;
                                    break;
                                case "Frm_CamCo":
                                    Forms.SoTraiChu.Frm_CamCo _Frm_CamCo = new Forms.SoTraiChu.Frm_CamCo(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_CamCo.ShowDialog();
                                    duyet = _Frm_CamCo._duyet;
                                    break;
                                case "Frm_GiaiCamCo":
                                    Forms.SoTraiChu.Frm_GiaiCamCo _Frm_GiaiCamCo = new Forms.SoTraiChu.Frm_GiaiCamCo(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_GiaiCamCo.ShowDialog();
                                    duyet = _Frm_GiaiCamCo._duyet;
                                    break;
                                case "Frm_MuaLai":
                                    Forms.SoTraiChu.Frm_MuaLai _Frm_MuaLai = new Forms.SoTraiChu.Frm_MuaLai(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_MuaLai.ShowDialog();
                                    duyet = _Frm_MuaLai._duyet;
                                    break;
                                case "Frm_NopTien":
                                    Forms.TKTienKH.Frm_NopTien _Frm_NopTien = new Forms.TKTienKH.Frm_NopTien(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_NopTien.ShowDialog();
                                    duyet = _Frm_NopTien._duyet;
                                    break;
                                case "Frm_RutTien":
                                    Forms.TKTienKH.Frm_RutTien _Frm_RutTien = new Forms.TKTienKH.Frm_RutTien(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_RutTien.ShowDialog();
                                    duyet = _Frm_RutTien._duyet;
                                    break;
                                case "Frm_PhongToaTien":
                                    Forms.TKTienKH.Frm_PhongToaTien _Frm_PhongToaTien = new Forms.TKTienKH.Frm_PhongToaTien(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_PhongToaTien.ShowDialog();
                                    duyet = _Frm_PhongToaTien._duyet;
                                    break;
                                case "Frm_GiaiToaTien":
                                    Forms.TKTienKH.Frm_GiaiToaTien _Frm_GiaiToaTien = new Forms.TKTienKH.Frm_GiaiToaTien(_tableTrans, Code.StaticVariable.function_Approve);
                                    _Frm_GiaiToaTien.ShowDialog();
                                    duyet = _Frm_GiaiToaTien._duyet;
                                    break;
                                default:
                                    break;
                            }

                            if (duyet == (int)Code.StaticVariable.approveCase.DaDuyet)//chấp nhập duyệt
                            {
                                //remove 2 column
                                _tableTrans.Columns.Remove("AUTOID");
                                //_tableTrans.Columns.Remove("IDGD");
                                _tableTrans.Columns.Remove("NGAYTAOGD");
                                DataTable noname = new DataTable("noname");
                                foreach (DataColumn col in _tableTrans.Columns)
                                {
                                    //bỏ qua 2 column này
                                    //if (col.ColumnName == "AUTOID" || col.ColumnName == "IDGD")
                                    //    continue;
                                    noname.Columns.Add(col.ColumnName, typeof(String)); //col.DataType
                                }

                                if (_tableTrans.Rows.Count > 0)
                                {
                                    for (int i = 0; i < _tableTrans.Rows.Count; i++)
                                    {

                                        noname.Clear();
                                        
                                        //create new row
                                        DataRow rowValue = noname.NewRow();
                                        DataRow rowType = noname.NewRow();
                                        
                                        //add value to row
                                        for (int j = 0; j < noname.Columns.Count; j++)
                                        {
                                            rowValue[j] = _tableTrans.Rows[i][j];
                                            if (_tableTrans.Columns[j].DataType == typeof(DateTime))
                                                rowType[j] = "D";
                                            else
                                                rowType[j] = "T";
                                            
                                        }
                                        noname.Rows.Add(rowValue);
                                        noname.Rows.Add(rowType);
                                        string _result = _cl._services.Excute_Store_Transaction(_store, noname);
                                        if (_result != "0")
                                            throw new Exception(_result);
                                    }

                                }
                                else
                                {
                                    MessageBox.Show(Code.StaticVariable.messeseboxLoi, Code.StaticVariable.messeseboxLuuY);
                                    return;
                                }

                                //chuyển trạng thái duyet 0 -> 1
                                bool b = _cl._services.Approve_Data(_formName, _ColumnName, _id, (int)Code.StaticVariable.approveCase.DaDuyet);
                                if (b)
                                    MessageBox.Show(Code.StaticVariable.messeseboxDuyetThanhCong, Code.StaticVariable.messeseboxLuuY);
                                else
                                    MessageBox.Show(Code.StaticVariable.messeseboxDuyetThatBai, Code.StaticVariable.messeseboxLuuY);

                                //cap nhat thong tin nguoi duyet
                                bool update = _cl._services.AddTransApprove(Code.StaticVariable.userID, _id);
                                if (!update)
                                    MessageBox.Show(Code.StaticVariable.messeseboxUpdateTLLogallError, Code.StaticVariable.messeseboxLuuY);
                                btnTimKiem_Click(sender, e);
                                return;
                            }
                        }
                        else
                        {
                            if (check == (int)Code.StaticVariable.approveCase.DaDuyet)
                                //dữ liệu đã được duyệt
                                MessageBox.Show(Code.StaticVariable.messeseboxDaDuyet, Code.StaticVariable.messeseboxLuuY);
                            else
                                //error
                                MessageBox.Show(Code.StaticVariable.messeseboxLoi, Code.StaticVariable.messeseboxLuuY);
                        }
                    }
                    else
                    {
                        if (check == (int)Code.StaticVariable.approveCase.DaDuyet)
                            //dữ liệu đã được duyệt
                            MessageBox.Show(Code.StaticVariable.messeseboxDaDuyet, Code.StaticVariable.messeseboxLuuY);
                        else
                            //error
                            MessageBox.Show(Code.StaticVariable.messeseboxLoi, Code.StaticVariable.messeseboxLuuY);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }

        // khi USER click vào gridview, kiểm tra xem bản ghi được duyệt hay ko + có đc quyền duyệt hay không mới cho hiện nút duyệt
        private void dgvResult_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string _id = this.dgvResult.SelectedRows[0].Cells["AUTOID"].Value.ToString();
                string _ColumnName = this.dgvResult.Columns[0].Name;
                string _menuid = this.dgvResult.SelectedRows[0].Cells["menuid"].Value.ToString();
                int duyet = _cl._services.CheckApprove(_formName, _ColumnName, _id);
                //if (duyet == (int)Code.StaticVariable.approveCase.ChuaDuyet)
                //{
                    // nếu giao dịch chưa được duyet, kiêm tra quyền USER xem có đc duyệt hay ko
                    foreach (DataRow row_j in Code.StaticVariable.tablePermission.Rows)
                    {
                        if (_menuid == Convert.ToString(row_j["menuid"]))
                        {
                            string _authcode = Convert.ToString(row_j["authcode"]);
                            // kiểm tra nếu là trống thì ko show ra giao dịch này
                            if (_authcode == "")
                            {
                                btnApprove.Enabled = false;
                                btnDelete.Enabled = false;
                                btnReject.Enabled = false;
                            }
                            else
                            {
                                // kiểm tra nếu là N ( không có quyền duyet) thì ko show nut duyet giao dịch nay
                                if (_authcode.ToCharArray()[6] == 'Y')
                                {
                                    btnApprove.Enabled = true;
                                    btnReject.Enabled = true;
                                }
                                else
                                {
                                    btnApprove.Enabled = false;
                                    btnReject.Enabled = false;
                                }

                                //quyen xoa
                                if (_authcode.ToCharArray()[3] == 'Y')
                                {
                                    btnDelete.Enabled = true;
                                }
                                else
                                {
                                    btnDelete.Enabled = false;
                                }
                            }
                            break;
                        }
                    } 
                //}
                //else
                //{
                //    btnApprove.Enabled = false;
                //}
            }
            catch (Exception ex)
            {
                btnApprove.Enabled = false;
                btnDelete.Enabled = false;
                btnReject.Enabled = false;
            }
        }

        void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex % 2 == 0)
            {
                e.CellStyle.BackColor = Color.FromArgb(195, 231, 195);
            }
            else
            {
                e.CellStyle.BackColor = Color.FromArgb(253, 240, 208);
            }
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            LoadTransData();
        }

        private bool Existed_DanhSachDieuKien(string _e)
        {
            for (int i = 0; i < this.clbDanhSachDieuKien.Items.Count; i++)
            {
                if (this.clbDanhSachDieuKien.Items[i].ToString().Contains(_e))
                {
                    return false;
                }
            }
            return true;
        }

        private void Like(DictionaryEntry item)
        {
            switch (this._fieldtype)
            {
                case "C":
                    if (_lookupcmdsql == "")
                    {
                        listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + this.txtGiaTriTimKiem.Text.ToUpper());
                    }
                    else
                        listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + ((KeyValuePair<string, string>)cbbGiaTri.SelectedItem).Key);
                    break;
                case "D":
                    this.listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + this.dtpGiaTri.Value.ToString("dd/MM/yyyy"));
                    break;
                default:
                    break;
            }
        }

        private void Equal(DictionaryEntry item)
        {
            switch (this._fieldtype)
            {
                case "C":
                    if (_lookupcmdsql == "")
                    {
                        listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + this.txtGiaTriTimKiem.Text.ToUpper());
                    }
                    else
                        listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + ((KeyValuePair<string, string>)cbbGiaTri.SelectedItem).Key);
                    break;
                case "D":
                    this.listDS_DK_TimKiem.Add(item.Key, this.cbbPhepToan.Text + "@@@" + this.dtpGiaTri.Value.ToString("dd/MM/yyyy"));
                    break;
                default:
                    break;
            }
        }

        private void Add()
        {
            if (this.txtGiaTriTimKiem.Visible)
                this.clbDanhSachDieuKien.Items.Add(this.cbbTieuChi.Text + " " + this.cbbPhepToan.Text + " '" + this.txtGiaTriTimKiem.Text + "'", true);
            else
                this.clbDanhSachDieuKien.Items.Add(this.cbbTieuChi.Text + " " + this.cbbPhepToan.Text + " '" + this.dtpGiaTri.Text + "'", true);

        }

        private void btnTruyenSang_Click(object sender, EventArgs e)
        {
            // Kiểm tra nếu đã có điều kiện này rồi thì ko gán sang nữa
            if (Existed_DanhSachDieuKien(cbbTieuChi.Text))
            {
                if (txtGiaTriTimKiem.Text.Trim().Length > 0 || this.dtpGiaTri.Text != "")
                {
                    // Gán giá trị tìm kiếm vào mảng
                    foreach (DictionaryEntry item in this.listTieuChi)
                    {
                        if (item.Value.ToString() == this.cbbTieuChi.Text && this.listDS_DK_TimKiem.ContainsKey(item.Key) == false)
                        {
                            //DATNT: kiểm tra phép toán điều kiện là gì
                            switch (cbbPhepToan.Text)
                            {
                                case "LIKE":
                                    //this.listDS_DK_TimKiem.Add(item.Key, item.Key + " " + this.cbbPhepToan.Text + " '%" + this.txtGiaTriTimKiem.Text + "%'");
                                    this.Like(item);
                                    break;
                                default:
                                    //this.listDS_DK_TimKiem.Add(item.Key, item.Key + " " + this.cbbPhepToan.Text + " '" + this.txtGiaTriTimKiem.Text + "'");
                                    this.Equal(item);
                                    break;
                            }
                            //end DATNT
                        }
                    }
                    // them vao phan hien thi
                    //DatNT: remove this.clbDanhSachDieuKien.Items.Clear();
                    //this.clbDanhSachDieuKien.Items.Add(this.cbbTieuChi.Text + " " + this.cbbPhepToan.Text + " '" + this.txtGiaTriTimKiem.Text + "'", true);
                    this.Add();
                    this.btnTimKiem.Focus();
                }
            }
        }

        private void btnTruyenVe_Click(object sender, EventArgs e)
        {
            if (this.clbDanhSachDieuKien.SelectedIndex >= 0)
            {
                //DATNT: bỏ trong mảng tìm kiếm
                // Gán giá trị tìm kiếm vào mảng
                foreach (DictionaryEntry item in this.listTieuChi)
                {
                    if (this.clbDanhSachDieuKien.SelectedItem.ToString().Contains(item.Value.ToString()))
                    {
                        this.listDS_DK_TimKiem.Remove(item.Key);
                        //end DATNT
                    }
                }

                // bỏ phần hiển thị
                this.clbDanhSachDieuKien.Items.Remove(this.clbDanhSachDieuKien.SelectedItem);
            }
        }

        private void btnTruyenVeHet_Click(object sender, EventArgs e)
        {
            this.clbDanhSachDieuKien.Items.Clear();
            this.listDS_DK_TimKiem.Clear();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (this.dgvResult.RowCount > 0)
            {
                Code.ExportUtility _ExportExcel = new Code.ExportUtility();
                _ExportExcel.Export(this.dgvResult);
            }
        }

        private void cbbTieuChi_SelectedIndexChanged(object sender, EventArgs e)
        {
            // lấy phép toán tương ứng với tiêu chí
            foreach (DataRow row in _tableTieuChi.Rows)
            {
                if (cbbTieuChi.Text == row["FIELDNAME"].ToString())
                {
                    _operator = row["OPERATOR"].ToString();
                    _fieldtype = row["FIELDTYPE"].ToString();
                    _lookupcmdsql = row["LOOKUPCMDSQL"].ToString();
                }
            }

            // xoa het Phep toan, add lại
            this.cbbPhepToan.Items.Clear();
            if (_operator.Contains(","))
            {
                string[] operator_mini = _operator.Split(',');
                for (int i = 0; i < operator_mini.Length; i++)
                {
                    cbbPhepToan.Items.Add(operator_mini[i]);
                }
                this.cbbPhepToan.SelectedIndex = 0;
            }

            // Ẩn hiện giá trị theo FieldType 
            ShowHide_GiaTri(_fieldtype, _lookupcmdsql);
        }

        private void ShowHide_GiaTri(string _fieldtype, string _lookupcmdsql)
        {
            // Nếu _lookupcmdsql có giá trị, kiểu C thì tức là combobox
            if (_lookupcmdsql == "")
            {
                switch (_fieldtype)
                {
                    case "C":
                        this.txtGiaTriTimKiem.Visible = true;
                        this.cbbGiaTri.Visible = false;
                        this.dtpGiaTri.Visible = false;
                        break;
                    case "D":
                        this.txtGiaTriTimKiem.Visible = false;
                        this.cbbGiaTri.Visible = false;
                        this.dtpGiaTri.Visible = true;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (_fieldtype)
                {
                    case "C":
                        this.txtGiaTriTimKiem.Visible = false;
                        this.cbbGiaTri.Visible = true;
                        Show_ComboboxGiaTri();
                        this.dtpGiaTri.Visible = false;
                        break;
                    case "D":
                        this.txtGiaTriTimKiem.Visible = true;
                        this.cbbGiaTri.Visible = false;
                        this.dtpGiaTri.Visible = false;
                        break;
                    default:
                        break;
                }
            }
        }

        private void Show_ComboboxGiaTri()
        {

            DataTable _result = _cl._services.GetDatatable_BySQL(_lookupcmdsql);
            //this.cbbGiaTri.Items.Clear();
            Dictionary<string, string> obj = new Dictionary<string, string>();
            foreach (DataRow row in _result.Rows)
            {
                //this.cbbGiaTri.Items.Add(row["DISPLAY"].ToString());

                obj.Add(row["VALUE"].ToString(), row["DISPLAY"].ToString());
                this.cbbGiaTri.DataSource = new BindingSource(obj, null);
                this.cbbGiaTri.DisplayMember = "Value";
                this.cbbGiaTri.ValueMember = "Key";
                this.cbbGiaTri.SelectedIndex = 0;
            }
            this.cbbGiaTri.SelectedIndex = 0;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // lấy ID của row được chọn
                string _id = this.dgvResult.SelectedRows[0].Cells["AUTOID"].Value.ToString();
                string _CulumnName = this.dgvResult.Columns[0].Name;
                if (MessageBox.Show(Code.StaticVariable.messeseboxXoaRow, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    string result = _cl._services.DeleteRow(_formName, _id, _CulumnName, Code.StaticVariable.userID);

                    if (result == "OK")
                    {
                        //cap nhat thong tin nguoi duyet
                        bool update = _cl._services.AddTransApprove(Code.StaticVariable.userID, _id);
                        if (!update)
                           throw new Exception(Code.StaticVariable.messeseboxUpdateTLLogallError);

                        MessageBox.Show(Code.StaticVariable.messeseboxThanhCong, this._formName, MessageBoxButtons.OK);
                    }
                    else
                        MessageBox.Show(result, this._formName, MessageBoxButtons.OK);
                    btnTimKiem_Click(sender, e);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }

        private void btnReject_Click(object sender, EventArgs e)
        {
            try
            {
                // lấy ID của row được chọn
                string _id = this.dgvResult.SelectedRows[0].Cells["AUTOID"].Value.ToString();
                string _columnName = this.dgvResult.Columns[0].Name;
                int check = _cl._services.CheckApprove(_formName, _columnName, _id);

                DialogResult result = MessageBox.Show(Code.StaticVariable.messeseboxHuyDuyet, Code.StaticVariable.messeseboxLuuY, MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    if (check == (int)Code.StaticVariable.approveCase.ChuaDuyet)
                    {
                        Forms.FrmRejectTransaction _frmReject = new Forms.FrmRejectTransaction(_formName, _columnName, _id);
                        _frmReject.ShowDialog();
                        btnTimKiem_Click(sender, e);
                    }
                    else
                        MessageBox.Show(Code.StaticVariable.messeseboxHuyDuyetKoThanhCong, Code.StaticVariable.messeseboxLuuY);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }


        //06-08-2017:DATNT thêm chức năng xem
        private void btnView_Click(object sender, EventArgs e)
        {
            int magiaodich = Convert.ToInt16(this.dgvResult.SelectedRows[0].Cells["MAGIAODICH"].Value.ToString());
            string _id = this.dgvResult.SelectedRows[0].Cells["AUTOID"].Value.ToString();
            string _ColumnName = this.dgvResult.Columns[0].Name;
            string _tblName = "";
            string _store = "";

            //thực thi giao dịch
            switch (magiaodich)
            {
                case 203:
                    _tblName = "BSC_TBL_CHUYENNHUONG";
                    _store = "bsc_203.Chuyen_nhuong";
                    break;
                case 207:
                    _tblName = "BSC_TBL_PHONGTOA";
                    _store = "bsc_207.Phong_toa_tp";
                    break;
                case 208:
                    _tblName = "BSC_TBL_GIAIPHONGTOA";
                    _store = "bsc_208.Giai_toa_tp";
                    break;
                case 209:
                    _tblName = "BSC_TBL_CAMCO";
                    _store = "bsc_209.Cam_co_tp";
                    break;
                case 210:
                    _tblName = "BSC_TBL_GIAICAMCO";
                    _store = "bsc_210.Giai_cam_co_tp";
                    break;
                case 211:
                    _tblName = "BSC_TBL_MUALAI";
                    _store = "bsc_211.Mua_lai_tp";
                    break;
                case 602:
                    _tblName = "BSC_TBL_NOPTIEN";
                    _store = "bsc_602.Nop_tien_mat";
                    break;
                case 603:
                    _tblName = "BSC_TBL_RUTTIEN";
                    _store = "bsc_603.Rut_tien_mat";
                    break;
                case 604:
                    _tblName = "BSC_TBL_PHONGTOATIEN";
                    _store = "bsc_604.Phong_toa_tien";
                    break;
                case 605:
                    _tblName = "BSC_TBL_GIAITOATIEN";
                    _store = "bsc_605.Giai_toa_tien";
                    break;

                default:
                    break;
            }

            if (_tblName.Length == 0)
               throw new Exception("Không có giao dịch này!");
            //get table transaction data  "select c.*,t.ngaytaogd from " + _tblName + " c, " + _formName + " t  where c.idgd = t.autoid and c.IDGD ='" + _id + "'"
            _tableTrans = _cl._services.GetDatatable_BySQL("select c.*,t.ngaytaogd from " + _tblName + " c, " + _formName + " t  where c.idgd = t.autoid and c.IDGD ='" + _id + "'");

            //show lại màn hình giao dịch cho dvck xem lại
            DataTable dt = _cl._services.GetMenu_ByMenuCode(Convert.ToString(magiaodich));
            if (dt.Rows.Count > 0)
            {
                string _formname = Convert.ToString(dt.Rows[0]["formname"]);
                switch (_formname)
                {
                    case "Frm_ChuyenNhuong":
                        Forms.SoTraiChu.Frm_ChuyenNhuong _Frm_ChuyenNhuong = new Forms.SoTraiChu.Frm_ChuyenNhuong(_tableTrans,Code.StaticVariable.function_View);
                        _Frm_ChuyenNhuong.ShowDialog();
                        break;
                    case "Frm_PhongToa":
                        Forms.SoTraiChu.Frm_PhongToa _Frm_PhongToa = new Forms.SoTraiChu.Frm_PhongToa(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_PhongToa.ShowDialog();
                        break;
                    case "Frm_GiaiPhongToa":
                        Forms.SoTraiChu.Frm_GiaiPhongToa _Frm_GiaiPhongToa = new Forms.SoTraiChu.Frm_GiaiPhongToa(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_GiaiPhongToa.ShowDialog();
                        break;
                    case "Frm_CamCo":
                        Forms.SoTraiChu.Frm_CamCo _Frm_CamCo = new Forms.SoTraiChu.Frm_CamCo(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_CamCo.ShowDialog();
                        break;
                    case "Frm_GiaiCamCo":
                        Forms.SoTraiChu.Frm_GiaiCamCo _Frm_GiaiCamCo = new Forms.SoTraiChu.Frm_GiaiCamCo(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_GiaiCamCo.ShowDialog();
                        break;
                    case "Frm_MuaLai":
                        Forms.SoTraiChu.Frm_MuaLai _Frm_MuaLai = new Forms.SoTraiChu.Frm_MuaLai(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_MuaLai.ShowDialog();
                        break;
                    case "Frm_NopTien":
                        Forms.TKTienKH.Frm_NopTien _Frm_NopTien = new Forms.TKTienKH.Frm_NopTien(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_NopTien.ShowDialog();
                        break;
                    case "Frm_RutTien":
                        Forms.TKTienKH.Frm_RutTien _Frm_RutTien = new Forms.TKTienKH.Frm_RutTien(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_RutTien.ShowDialog();
                        break;
                    case "Frm_PhongToaTien":
                        Forms.TKTienKH.Frm_PhongToaTien _Frm_PhongToaTien = new Forms.TKTienKH.Frm_PhongToaTien(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_PhongToaTien.ShowDialog();
                        break;
                    case "Frm_GiaiToaTien":
                        Forms.TKTienKH.Frm_GiaiToaTien _Frm_GiaiToaTien = new Forms.TKTienKH.Frm_GiaiToaTien(_tableTrans, Code.StaticVariable.function_View);
                        _Frm_GiaiToaTien.ShowDialog();
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
